package com.tonicgb.shared.handler;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.tonicgb.shared.annotation.ApiResponse;
import com.tonicgb.shared.common.response.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author zhaiyujin
 * @date 2021-09-06 23:53:21
 * @说明 自定义返回数据处理类
 */
public class ApiResultHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler {
    private ObjectMapper objectMapper;

    public ApiResultHandlerMethodReturnValueHandler(ObjectMapper objectMapper){
        //将null转换成字符串“”
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
        this.objectMapper=objectMapper;
    }
    //创建jakson 创建ObjectMappter对象
//    private ObjectMapper objectMapper = new ObjectMapper();
//
//    {
////        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");objectMapper.setDateFormat(dateFormat);
//        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
//        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
//        SimpleModule simpleModule = new SimpleModule();
//        //序列化将Long转String 解决17位精度丢失问题
//        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
//        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
//        objectMapper.registerModule(simpleModule);
//        //为mapper注册一个带有SerializerModifier的Factory，此modifier主要做的事情为：当序列化类型为array，list、set时，当值为空时，序列化成[]
//         objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(new NullValueBeanSerializerModifier()));
//
//    }

    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        //方法使用@ApiResponse生效
        return methodParameter.getMethodAnnotation(ApiResponse.class)!=null;
    }

    @Override
    public void handleReturnValue(Object o, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws Exception {
        Result result= Result.success(o);
        modelAndViewContainer.setRequestHandled(true);
        HttpServletResponse response = (HttpServletResponse) nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.addHeader(HttpHeaders.CACHE_CONTROL, CacheControl.noCache().getHeaderValue());
        response.getWriter().append(objectMapper.writeValueAsString(result));
    }
}
